const request = require('request')
var NodeCache = require('node-cache') ;
var wxconfig = require('./wxconfig');
var myCache = new NodeCache({  stdTTL :3600 ,  checkperiod :3600 });
// 加载这个模块的时候给 ACCESS_TOKEN 这个键名初始化
var getAccessToken = function() {
    return new Promise(function (resolve, reject) {
        var tempToken = myCache.get( "ACCESS_TOKEN" );
        if(tempToken){
            resolve(tempToken)
        }else {
            request.get({
                uri: wxconfig.accessLink,
                json: true,
                qs: {
                    grant_type: 'client_credential',
                    appid: wxconfig.appid,    // APPID请换成你的 appid
                    secret: wxconfig.secret    // APPSECRET请换成你的 appsecret
                }
            }, (err, res, body) => {
                if (err) {
                    reject(err)
                }
                if (body.errcode) {
                    reject(body.errcode)
                }
                myCache.set('ACCESS_TOKEN',body.access_token,function(err,success){
                    if( !err && success ){
                        var  tempvalue = myCache.get( "ACCESS_TOKEN" );
                        resolve(tempvalue)
                    }
                })
            })
        }
    })
}
// 只要向外暴露一个获取值的方法就可以了
module.exports = getAccessToken
